#include <fonts_manager.h>
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H
#include <config.h>


static int FreetypeFontInit(char *FileName, unsigned int dwFontSize);
static int FreetypeGetFontBitmap(unsigned int dwCode, PT_Bitmap ptBitmap);

static FT_Library g_tLibrary;
static FT_Face g_tFace;
static FT_GlyphSlot g_tSlot;

static T_FontOpr g_tFreetypeFontOpr = {
	.name = "freetype",
	.FontInit = FreetypeFontInit,
	.GetFontBitmap = FreetypeGetFontBitmap,
};

static int FreetypeFontInit(char *FileName, unsigned int dwFontSize)
{
	int iError;
	
	iError = FT_Init_FreeType(&g_tLibrary);			   /* initialize library */
	if (iError)
	{
		DEG_PRINTF("FT_Init_FreeType failed\n");
		return -1;
	}

	iError = FT_New_Face(g_tLibrary, FileName, 0, &g_tFace); /* create face object */
	if (iError)
	{
		DEG_PRINTF("FT_Init_FreeType failed\n");		
		return -1;
	}

	g_tSlot = g_tFace->glyph;
	
	iError = FT_Set_Pixel_Sizes(g_tFace, dwFontSize, 0);
	if (iError)
	{
		DEG_PRINTF("FT_Set_Pixel_Sizes failed : %d\n", dwFontSize);
		return -1;
	}

	return 0;
}

static int FreetypeGetFontBitmap(unsigned int dwCode, PT_Bitmap ptBitmap)
{
	int iError;
	int iPenX = ptBitmap->iCurOriginX;
	int iPenY = ptBitmap->iCurOriginY;

	iError = FT_Load_Char(g_tFace, dwCode, FT_LOAD_RENDER | FT_LOAD_MONOCHROME);
	if (iError)
	{
		DEG_PRINTF("FT_Load_Char error for code : 0x%x\n", dwCode);
		return -1;
	}
	
	ptBitmap->iXLeft    = iPenX + g_tSlot->bitmap_left;
	ptBitmap->iYTop     = iPenY - g_tSlot->bitmap_top;
	ptBitmap->iXMax     = ptBitmap->iXLeft + g_tSlot->bitmap.width;
	ptBitmap->iYMax     = ptBitmap->iYTop  + g_tSlot->bitmap.rows;
	ptBitmap->iBpp      = 1;
	ptBitmap->iPitch    = g_tSlot->bitmap.pitch;
	ptBitmap->pucBuffer = g_tSlot->bitmap.buffer;
	
	ptBitmap->iNextOriginX = iPenX + g_tSlot->advance.x / 64;
	ptBitmap->iNextOriginY = iPenY;

	return 0;
}

int FreetypeFontRegister(void)
{
	return RegisterFontOpr(&g_tFreetypeFontOpr);
}


